package cn.ec.service;

import cn.ec.dao.DaoUtils;
import cn.ec.singleton.JsonMapper;
import cn.ec.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * 初始化时填入数据
 * 将指定表的数据全部填入Redis中
 */
@Slf4j
public class InitFillData {
    /**
     * 需要初始化的表列表
     */
    private static final String[] tableNames = new String[]{
            "t_agent", "t_customer", "t_location", "t_gateway", "t_node",
    };

    public static void init() throws SQLException {
        try {
            for (String tableName : tableNames) {
                List<Map<String, String>> stringObjectMaps = DaoUtils.selectByTableName(tableName);
                for (Map<String, String> stringObjectMap : stringObjectMaps) {
                    try {
                        String serialize = JsonMapper.INSTANCE.serialize(stringObjectMap);
                        System.out.println(serialize);
                        RedisUtil.hashSet(tableName, stringObjectMap.get("id"), serialize);
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("存入Redis失败[{}][{}]", stringObjectMap, e.getMessage());
                    }
                }
            }
        } finally {
            // 关闭数据库连接,因为只有在服务启动时需要用到数据库连接,之后再也不需要用到它了
            DaoUtils.conn.close();
        }
    }


}
